package com.aida.evil.eda.fragment;

import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.aida.evil.aida.R;
import com.aida.evil.eda.Data.NetworkData;
import com.aida.evil.eda.Data.SystemData;
import com.aida.evil.eda.Data.UserData;
import com.aida.evil.eda.Login.Encryp_AES;
import com.aida.evil.eda.MyView.CircleImageView;
import com.aida.evil.eda.Toast.CustomSuperActivityToast;
import com.aida.evil.eda.Volley.VolleyHandler;
import com.aida.evil.eda.Volley.VolleyHttpRequest;
import com.aida.evil.eda.Window.CustomDialog;
import com.dd.CircularProgressButton;
import com.evil.SMS.Data.SMS_Data;
import com.github.johnpersano.supertoasts.SuperToast;
import com.squareup.picasso.Picasso;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.smssdk.SMSSDK;
import cn.smssdk.gui.ContactsPage;

/****************************************************
 * com.aida.evil.eda.fragment.Shop
 * 作者：白雨濃  evil
 * 时间：16-2-17 10:43
 * 邮箱：evilbai@foxmail.com
 * 页面用途：包含分享信息，和流量兑换记录，流量兑换记录在Share_FlowRecord文件中
 ****************************************************/
public class Share extends Fragment
{
    private static final String SHAREURL = "http://" + NetworkData.ServiceIP + "/UserShare?";

    private CircleImageView circleImageView_1, circleImageView_2, circleImageView_3;/*顶部的3个圆形按钮*/
    private TextView circle_TextView_1, circle_TextView_2, circle_TextView_3;/*顶部3个圆形按钮的下部文字*/
    private LinearLayout linearLayout;

    protected View view;/*fragment的总视图*/

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        SMSSDK.initSDK(getContext(), "1177dd9f6b3e0", "4509651f324181882bdfb43445921ec5");
        ShareSDK.initSDK(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        view = inflater.inflate(R.layout.mainactivity_fragment_share, container, false);

        initView();/*初始化控件控件*/
        initTopViewData();/*初始化顶部控件数据*/
        Share_FlowRecord.load(view,getContext());/*加载流量兑换记录*/
        onClick();

        return view;
    }


    /**
     * 查找控件
     */
    private void initView()
    {
        circleImageView_1 = (CircleImageView) view
                .findViewById(R.id.mainactivity_fragment_share_circleImageView1);
        circleImageView_2 = (CircleImageView) view
                .findViewById(R.id.mainactivity_fragment_share_circleImageView2);
        circleImageView_3 = (CircleImageView) view
                .findViewById(R.id.mainactivity_fragment_share_circleImageView3);

        circle_TextView_1 = (TextView) view.findViewById(R.id.mainactivity_fragment_share_textView1);
        circle_TextView_2 = (TextView) view.findViewById(R.id.mainactivity_fragment_share_textView2);
        circle_TextView_3 = (TextView) view.findViewById(R.id.mainactivity_fragment_share_textView3);

        linearLayout = (LinearLayout) view.findViewById(R.id.mainactivity_fragment_share_linearLayout);

    }

    /**
     * 初始化顶部按钮
     */
    private void initTopViewData()
    {
        Picasso.with(getContext()).load(R.mipmap.share_exchange).into(circleImageView_1);
        circle_TextView_1.setText("邀请码填写");
        Picasso.with(getContext()).load(R.mipmap.share_share).into(circleImageView_2);
        circle_TextView_2.setText("分享链接");
        Picasso.with(getContext()).load(R.mipmap.share_address).into(circleImageView_3);
        circle_TextView_3.setText("通讯录分享");
    }

    /**
     * 顶部按钮监听
     */
    private void onClick()
    {
        circleImageView_1.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // SuperToast_Base.superActivityToast_Button(getActivity(), "积分兑换功能暂未开启，敬请期待！", "确定").show();

                setShare();
            }
        });
        circleImageView_2.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                showShare();
            }
        });
        circleImageView_3.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                ContactsPage contactsPage = new ContactsPage();
                contactsPage.show(getContext());
                SMS_Data.SMS_BODY = SystemData.SHARE_CONTEXT;
            }
        });

        linearLayout.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Log.i("", "");
            }
        });
    }

    /**
     * 邀请码填写
     */
    private void setShare()
    {
        CustomDialog.Builder builder = new CustomDialog.Builder(getContext());
        builder.setTitle("邀请码填写");
        View view = View.inflate(getContext(), R.layout.dialog_setsharenum, null);
        builder.setContentView(view);
        builder.show();

        final EditText setShare_EditText = (EditText) view.findViewById(R.id.dialog_setShareNum_editText);
        final EditText shareNum = (EditText) view.findViewById(R.id.dialog_setShareNum_editText2);
        final CircularProgressButton submit_Button = (CircularProgressButton) view.findViewById(R.id.dialog_setShareNum_submitButton);
        CircularProgressButton copy_Button = (CircularProgressButton) view.findViewById(R.id.dialog_setShareNum_copyButton);

        shareNum.setText(UserData.DATA_PHONENUM);

        submit_Button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if (UserData.DATA_PHONENUM.equals(setShare_EditText.getText().toString()))
                {
                    CustomSuperActivityToast.makeText(getActivity(), "您不能填写自己的手机号哦！", "确定"
                            , new SuperToast.OnClickListener()
                            {
                                @Override
                                public void onClick(View view, Parcelable token)
                                {
                                    setShare_EditText.setText("");
                                }
                            }).show();
                }
                else
                {
                    if (!setShare_EditText.getText().toString().equals(""))
                    {
                        if (submit_Button.getProgress() == -1 || submit_Button.getProgress() == 100)
                            submit_Button.setProgress(0);
                        else
                        {
                            submit_Button.setProgress(50);
                            setShare_toNetWork(submit_Button, setShare_EditText.getText().toString());
                        }
                    }
                }
            }
        });

        copy_Button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                ClipboardManager clipboardManager = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                clipboardManager.setText(shareNum.getText());
            }
        });


    }

    /**
     * 邀请码填写的网络请求
     */
    private void setShare_toNetWork(final CircularProgressButton submit_Button, String share)
    {
        VolleyHandler<String> stringVolleyHandler = new VolleyHandler<String>()
        {
            @Override
            public void reqSuccess(String response)
            {
                Toast toast = null;
                if (response.indexOf("ERROR:UNKNOW") != -1)
                {
                    submit_Button.setProgress(-1);
                    toast = Toast.makeText(getContext(), "抱歉，发生未知错误！", Toast.LENGTH_SHORT);

                }
                else if (response.indexOf("ERROR_NO_FOREIGN_KEY") != -1)
                {
                    submit_Button.setProgress(-1);
                    toast = Toast.makeText(getContext(), "没有此邀请码！", Toast.LENGTH_SHORT);
                }
                else if (response.indexOf("ERROR:OVER_GET") != -1)
                {
                    submit_Button.setProgress(-1);
                    toast = Toast.makeText(getContext(), "您已经填写过邀请码！", Toast.LENGTH_SHORT);
                }
                else if (response.indexOf("ERROR:INSERT_SHARE_NUM") != -1)
                {
                    submit_Button.setProgress(-1);
                    toast = Toast.makeText(getContext(), "您还未填写邀请码或邀请码错误！", Toast.LENGTH_SHORT);
                }
                else
                    submit_Button.setProgress(100);


                if (toast != null)
                {
                    toast.setGravity(Gravity.BOTTOM, 0, 0);
                    toast.show();
                }

            }

            @Override
            public void reqError(String error)
            {
                submit_Button.setProgress(-1);
            }
        };
        VolleyHttpRequest.String_request(SHAREURL + "userPhoneNum="
                + UserData.DATA_PHONENUM + "&share=" + share, stringVolleyHandler);
    }

    /**
     * 分享
     */

    private void showShare()
    {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("Eda易答换取邯郸移动流量");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://" + NetworkData.ServiceIP + "/Update?");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我正在使用Eda易答来答题换取流量，"
                + "快来一起happy吧！这是我的邀请码："
                + Encryp_AES.getAESCode(UserData.DATA_PHONENUM)
                + " 。填写邀请码我们两个都能获得额外的积分哦，积分可以换取"
                + "邯郸移动流量！\n下载地址：" + "http://" + NetworkData.ServiceIP + "/Update");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImageUrl("http://" + NetworkData.ServiceIP + "/EdaItem_Img?ItemImg=eda.png");//确保SDcard下面存在此张图片

        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://" + NetworkData.ServiceIP + "/Update");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://" + NetworkData.ServiceIP + "/Update");
        // 启动分享GUI
        oks.show(getActivity());
    }

}
